package com.duowan.mspider.download;


import java.io.Closeable;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver.Options;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.downloader.Downloader;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.PlainText;

public class MySeleniumDownloader implements Downloader, Closeable {
	private WebDriver webDriver;
	private Logger logger = Logger.getLogger(this.getClass());
	private int sleepTime = 0;
	private int poolSize = 1;

	public MySeleniumDownloader(String chromeDriverPath) {
		System.getProperties().setProperty("webdriver.chrome.driver", chromeDriverPath);
	}

	@Override
	public Page download(Request request, Task task) {
		this.checkInit(task);

		Site site = task.getSite();
		this.logger.info("downloading page " + request.getUrl());
		webDriver.get(request.getUrl());

		try {
			Thread.sleep((long) this.sleepTime);
		} catch (InterruptedException var9) {
			var9.printStackTrace();
		}

		Options manage = webDriver.manage();
		if (site.getCookies() != null) {
			Iterator var6 = site.getCookies().entrySet().iterator();

			while (var6.hasNext()) {
				Entry<String, String> cookieEntry = (Entry) var6.next();
				Cookie cookie = new Cookie((String) cookieEntry.getKey(), (String) cookieEntry.getValue());
				manage.addCookie(cookie);
			}
		}

		WebElement webElement = webDriver.findElement(By.xpath("/html"));
		String content = webElement.getAttribute("outerHTML");
		Page page = new Page();
		page.setRawText(content);
		page.setHtml(new Html(content, request.getUrl()));
		page.setUrl(new PlainText(request.getUrl()));
		page.setRequest(request);
		return page;
	}

	private void checkInit(Task task) {
		Site site = task.getSite();
		if (this.webDriver == null) {
			synchronized (this) {
				try {
					//声明chromeoptions,主要是给chrome设置参数
					ChromeOptions options = new ChromeOptions();
					//设置user agent为iphone5
					options.addArguments("--user-agent=" + site.getUserAgent());
					//实例化chrome对象，并加入选项
					webDriver = new ChromeDriver(options);
				} catch (Exception var10) {
					this.logger.warn("interrupted", var10);
				}
			}
		}
	}

	@Override
	public void setThread(int thread) {
		this.poolSize = thread;
	}

	@Override
	public void close() throws IOException {
		webDriver.close();
	}
}
